package cn.mesmile.activity.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.mesmile.activity.mapper.CommentMapper;
import cn.mesmile.activity.service.CommonService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zb
 * @date 2021/12/23 10:02
 * @Description
 */
@Slf4j
@AllArgsConstructor
@Service
public class CommonServiceImpl implements CommonService {

    private final RepositoryService repositoryService;

    private final RuntimeService runtimeService;

    private final TaskService taskService;

    private final IdentityService identityService;

    private final CommentMapper commentMapper;

    @Override
    public Deployment deployProcess() {
        Deployment deploy = repositoryService.createDeployment()
                .category("person_category")
                .addClasspathResource("test.bpmn20.xml")
                .name("vacationName")
                .key("vacation_key")
                .deploy();
        return deploy;
    }

    @Override
    public ProcessInstance startProcess() {
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("employeeName", "张三");
        variables.put("numberOfDays", 4);
        variables.put("vacationMotivation", "这是请假的原因哦");

        identityService.setAuthenticatedUserId("0000001");

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("vacationRequest", variables);
        return processInstance;
    }

    @Override
    public void queryTask() {
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("management").list();
        for (Task task : tasks) {
            log.info("Task available: " + task.getName());
            log.info("Task available: " + task.getAssignee());
            log.info("Task available: " + task.getName());
            log.info("Task available: " + task.getCategory());
        }
    }

    @Override
    public void completeTask() {
        runtimeService.deleteProcessInstance("流程实例id", "终止/删除原因");
        List<Task> tasks = taskService.createTaskQuery().list();
        if (CollUtil.isNotEmpty(tasks)){
            Task task = tasks.get(0);
            Map<String, Object> taskVariables = new HashMap<String, Object>();
            taskVariables.put("vacationApproved", "false");
            taskVariables.put("managerMotivation", "表示不同意");

            taskService.complete(task.getId(), taskVariables);
        }
    }

    @Override
    public String getXml(String processDefinitionId) {
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        BpmnXMLConverter converter = new BpmnXMLConverter();
        //把bpmnModel对象转换成字符
        byte[] bytes = converter.convertToXML(bpmnModel);
        String xmlContenxt = new String(bytes);
        return xmlContenxt;
    }

    @Override
    public void stopProcess(String processInstanceId) {
        runtimeService.deleteProcessInstance(processInstanceId, "终止/删除流程原因："+processInstanceId);
    }

    @Override
    public void findComment(String taskId) {
        // select * from ACT_HI_COMMENT where TASK_ID_ = ? and TYPE_ = 'comment' order by TIME_ desc
        List<Comment> commentList = taskService.getTaskComments(taskId);

        // 自定义sql查询
        String sqlQuery = "select * from ACT_HI_COMMENT where TASK_ID_ = ? order by TIME_ desc";
        List<Comment> commentList2 = commentMapper.selectCommentByTaskId(taskId);

        for (Comment comment : commentList) {
            String type = comment.getType();
            String userId = comment.getUserId();
            String fullMessage = comment.getFullMessage();
            log.info(">>>>>>>>> type:{}, userId:{}, fullMessage:{}",type, userId, fullMessage);
        }
    }

    @Override
    public Boolean isMultiInstance(String taskKey, String processDefId) {
        boolean isMultiInstance = false;
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefId);
        Process mainProcess = bpmnModel.getMainProcess();
        FlowElement flowElement = mainProcess.getFlowElement(taskKey);
        if (flowElement instanceof UserTask) {
            UserTask userTask = (UserTask) flowElement;
            if (userTask.getBehavior() instanceof ParallelMultiInstanceBehavior) {
                ParallelMultiInstanceBehavior behavior = (ParallelMultiInstanceBehavior) userTask.getBehavior();
                if (behavior != null && behavior.getCollectionExpression() != null) {
                    isMultiInstance = true;
                }
            }
        }
        return isMultiInstance;
    }


}
